﻿using MIO.Client.Daemon;
using MIO.Client.Protocal;
using MIO.Client.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MIO.Client
{
    public class PacketHandler
    {
        private IOClient client;

        public IOClient Client
        {
            get { return client; }
            private set { client = value; }
        }


        public PacketHandler(IOClient client)
        {
            Client = client;
        }


        public void messageReceived(byte[] buff, int len)
        {
            string packetJsonString = CharsetHelper.getString(buff, len);
            Packet packet = JsonUtil.jsonString2Object<Packet>(packetJsonString);

            switch (packet.Type)
            {
                case PacketType.KEEP_ALIVE:
                    {
                        Task.Factory.StartNew(()=> {
                            Client.KeepAliveDaemon.updateGetKeepAliveResponseFromServerTimstamp();
                        });
                        
                        break;
                    }
                case PacketType.ACK:
                    { 
                        Client.AckSendTask.remove(Client,packet.AckId);
                        break;
                    }
                case PacketType.EVENT_MESSAGE:
                    {
                        checkAndSendAckPakcet(client, packet);
                        if (!Client.AckReceiveTask.hasRecieved(packet.AckId))
                        {
                            Client.AckReceiveTask.put(packet.AckId);
                            Client.EventManager.onEvent(client, packet.SubType, packet.SessionId, packet.DataContent);
                        }

                        break;
                    }
                default:
                    break;
            }
        }

        private void checkAndSendAckPakcet(IOClient client, Packet packet)
        {
            if (packet.Ack && !string.IsNullOrEmpty(packet.AckId))
            {
                Packet ackPacket = packet.clone();
                ackPacket.Type = PacketType.ACK; 
                client.send(ackPacket);
            }
        }

    }
}
